package com.pozu.new_retail.controllers;

import com.alibaba.fastjson.JSONObject;
import com.pozu.new_retail.dao.base.JsonResult;
import com.pozu.new_retail.dao.model.*;
import com.pozu.new_retail.dao.vo.UserVo;
import com.pozu.new_retail.service.*;
import com.pozu.new_retail.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

@Controller
public class UserController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private CodeService codeService;
	@Autowired
	private FavoriteRecordService favoriteRecordService;
	@Autowired
	private CommentService commentService;
	@Autowired
	private UgcService ugcService;
	@Autowired
	private ShoppingCartService shoppingCartService;

	@ResponseBody
	@RequestMapping(value = "/api/users", method = RequestMethod.POST)
	public Object login(HttpServletRequest request) throws Exception{
		
		int appId = Integer.parseInt(request.getHeader("appId"));//那个小程序
		
		int channelId = request.getHeader("channelId")==null?1:Integer.parseInt(request.getHeader("channelId"));//渠道
		
		User requestUser = Tools.getRequestObject(request, User.class);
		
		String phone = requestUser.getPhone();//带国家代码的手机号
		
		JsonResult jr = new JsonResult();
		
		UserVo userVo = userService.queryByPhone(phone);
		if(null == userVo){
			LogUtils.INFO.info("{}新注册用户",phone);
			requestUser.setAppId(appId);
			requestUser.setChannelId(channelId);
			
			if (null == requestUser.getNickName() || "".equals(requestUser.getNickName())) {
				requestUser.setNickName(phone);
			}
			
			userService.saveUser(requestUser);	
			userVo = userService.queryByPhone(phone);
		}else {
			
			HashMap<String, Object> hashMap = new HashMap<String,Object>();
			
			hashMap.put("appId", appId);
			hashMap.put("userId", userVo.getUserId());
			
			userVo.setCommentOnMeNumber(commentService.queryMyCountByUserId(hashMap));	
			
			userVo.setMyUgcNumber(ugcService.queryMyCountByUserId(hashMap));

			userVo.setShoppingCartGoodsNumber(shoppingCartService.queryMyCountByUserId(hashMap));

			hashMap.put("type", 0);
			
			userVo.setFavoriteGoodsNumber(favoriteRecordService.queryMyCountByMap(hashMap));
			
			hashMap.put("type", 1);
			
			userVo.setFavoriteUgcNumber(favoriteRecordService.queryMyCountByMap(hashMap));
			
			Code codeObj = codeService.queryCodeObjByUserId(appId, userVo.getUserId());
			if (null!=codeObj) {
				userVo.setCode(codeObj.getCode());
				userVo.setType(codeObj.getLevel());
			}
		}
		jr.respCode = CodeConstants.SUCCESS_CODE;
		jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
		jr.respData = userVo;
		
		return jr;
	}

	@ResponseBody
	@RequestMapping(value = "/api/users", method = RequestMethod.PUT)
	public Object update(HttpServletRequest request) throws Exception{
		
		long userId = Long.parseLong(request.getHeader("userId"));
		
		User requestUser = Tools.getRequestObject(request, User.class);
		
		JsonResult jr = new JsonResult();
		
		User user = userService.queryByUserId(userId);
		
		if(null == user){
			jr.respCode = CodeConstants.USERNOTEXISTED_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.USERNOTEXISTED_MSG);
			LogUtils.INFO.info("{}user不存在",requestUser.getUserId());
			return jr;
		}
		
		requestUser.setUserId(userId);
		userService.updateUser(requestUser);
		
		jr.respCode = CodeConstants.SUCCESS_CODE;
		jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
		jr.respData = userService.queryByUserId(userId);
		return jr;
	}

	@ResponseBody
	@RequestMapping(value = "/api/users/list", method = RequestMethod.GET)
	public Object getUsers(HttpServletRequest request) throws Exception{
		
		int appId = Integer.parseInt(request.getHeader("appId"));//那个小程序
		
		int pageStart = Integer.parseInt(request.getParameter("pageStart"));//第几页从0开始
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));//一页显示几条数据
		
		HashMap<String, Object> map = new HashMap<String, Object>();

		map.put("pageStart", pageStart*pageSize);
		map.put("pageSize", pageSize);
		map.put("appId", appId);
		
		JsonResult jr = new JsonResult();
		
		jr.respCode = CodeConstants.SUCCESS_CODE;
		jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
		jr.respData = userService.queryUsersByMap(map);
		
		return jr;
	}

	@ResponseBody
	@RequestMapping(value = "/api/users/phone", method = RequestMethod.POST)
	public Object updateByWxPhone(HttpServletRequest request) throws Exception{
		Map<String, Object> requestData = Tools.getRequestData(request);
		int appId = Integer.parseInt(request.getHeader("appId"));
		long userId = Long.parseLong(request.getHeader("userId"));
		String encryptedData = requestData.get("encryptedData").toString();
		String iv = requestData.get("iv").toString();
		User user = userService.queryByUserId(userId);
		JsonResult jr = new JsonResult();
		if (user != null){
			JSONObject jsonObject = WXUtils.getUserInfo(encryptedData, user.getWxSession_key(), iv);
			//用户存在
			String phone = jsonObject.getString("phoneNumber");
			if(phone == null){
				//更新手机号失败
				jr.respCode = CodeConstants.USEPHONEUPDATEFAIL_MSG;
				jr.respMsg = CodeProperties.getString(CodeConstants.USEPHONEUPDATEFAIL_MSG);
				LogUtils.INFO.info("手机号更新失败",userId);
				return jr;
			}else{
				user.setPhone(phone);
				System.out.print("解密出来的数据"+jsonObject);
				userService.updateUser(user);
				jr.respCode = CodeConstants.SUCCESS_CODE;
				jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
				jr.respData = user;
				return jr;
			}
		}else{
			//用户不存在
			jr.respCode = CodeConstants.USERNOTEXISTED_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.USERNOTEXISTED_MSG);
			LogUtils.INFO.info("{}user不存在",userId);
			return jr;
		}
	}
}
